package sjg.tenNormalAlgorithm.binarySearch;

/**
 * 非递归 二分查找算法
 * 前提： 数组有序
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int[] arr = {1, 3, 8, 10, 11, 67, 100};
        int index = binarySearchNoCur(arr, 1);
        System.out.println(index);
    }

    private static int binarySearchNoCur(int[] arr, int target) {
        int right = arr.length - 1;
        int left = 0;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] < target) {
                left = mid + 1;
            } else if (target < arr[mid]) {
                right = mid - 1;
            } else {// 匹配到值，直接返回
                return mid;
            }
        }
        return -1;
    }


}
